// 获取应用实例
import util from "../../utils/util"
import api from '../../utils/Api'
import Dialog from '@vant/weapp/dialog/dialog'
import {
  saveMatter,
  nmgsmzgl,
  getClickInfoForCode,
  refreshQrcode
} from '../../utils/my'
import {
  queryTempFunctionCode,
  getJsapiTicket
} from '../../utils/login'
import {
  encryptAES
} from '../../utils/encryption'
const app = getApp()
const envVersion = wx.getAccountInfoSync().miniProgram.envVersion; //获取版本
Page({
  data: {
    envVersion: envVersion,
    userInfo: wx.getStorageSync('userInfo'),
    showUserInfoComplete: false, //是否显示完整的用户信息
    menuInfo: {},
    headHeight: 0,
    newsinfo: '',
    page: 1,
    limit: 5,
    total: 0,
    login_identification: true,
    address_List: ['南京市', '苏州市', '常州市', '无锡市', '盐城市'], //地区选择
    address: '南京市',
    otherService: [
      // {
      //   title: '社会保障卡',
      //   English: 'BAO ZHANG KA',
      //   url: '/pages/SocialSecurityCard/SocialSecurity_all/SocialSecurity_all',
      //   icon: 'home1'
      // },
      // {
      //   title: '社保查询',
      //   English: 'SHE BAO CHA XUN',
      //   url: '/pages/SocialInsurance/SocialInsurance_all/SocialInsurance_all',
      //   icon: 'home10',
      //   isShow: true
      // },
      {
        title: '我的社保',
        English: 'WO DE SHE BAO',
        url: '/pages/SocialInsurance/SocialInsurance_all/SocialInsurance_all',
        icon: 'home10',
        isShow: true,
        type: '2',
        code: 'OTHER_0031',
      },
      {
        title: '个人权益单',
        English: 'GE REN QUAN YI',
        url: '/pages/EquityForm/EquityForm_all/EquityForm_all',
        type: '2',
        code: 'SHBX_0024',
        icon: 'home11',
        isShow: true
      },
      {
        title: '人社智慧大屏',
        English: 'ZHI HUI DA PING',
        icon: 'home12',
        type: '3',
        url: 'https://njrsxxzx.cn/zwapp-ui/index.html#/layout/home?loginType=njWechatAuth&token=' + wx.getStorageSync('accessToken'),
        isShow: envVersion == 'develop' || envVersion == 'trial'
      },
      {
        title: '人社服务圈',
        English: 'REN SHE FU WU QUAN',
        url: '/pages/map/map',
        icon: 'home13',
        isShow: true
      }, {
        title: '求职招聘专区',
        English: 'QIU ZHI ZHAO PING',
        url: '/pages/Employment/employment',
        icon: 'home14',
        isShow: true
      },
    ],
    show: false,
    authCode: '',
    hideUserInfo: {},
    showQrCode: false,
    qrcode: '',
    validDate: '',
    refreshSeq: '',
    signNo: '',
    countdownText: '',
    countdownDone: true
  },
  changeUserInfoHanlder() {
    this.setData({
      showUserInfoComplete: !this.data.showUserInfoComplete
    })
    this.changeUserInfo()
  },
  //显示二维码
  showQrCode() {
    wx.showLoading({
      title: '加载中...',
    })
    getClickInfoForCode({
      sfz: this.data.userInfo.idNumber,
      phone: this.data.userInfo.cellphone,
      name: this.data.userInfo.name,
    }).then(res => {
      if (res.code == 101) {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '您没有申请电子社保卡，是否前往申请？',
          success: (res1) => {
            if (res1.confirm) {
              wx.navigateTo({
                url: '/pages/web_h5/web_h5?url=' + encodeURIComponent(res.url)
              })
            }
          }
        })
      } else if (res.code == 102) {
        wx.hideLoading()
        //返回的是base64的二维码 展示在页面上
        wx.navigateTo({
          url: '/pages/web_h5/web_h5?url=' + encodeURIComponent(res.url)
        })
      } else if (res.code == 100) {
        wx.hideLoading()
        //返回的是base64的二维码 展示在页面上
        this.setData({
          showQrCode: true,
          qrcode: res.qrcode,
          validDate: res.validDate,
          signNo: res.signNo,
          refreshSeq: res.refreshSeq
        })
        this.startQrCountdown(res.validDate)
      } else {
        wx.showToast({
          title: '二维码生成失败',
          icon: 'error'
        })
      }
    }).finally(() => {

    })
  },
  refreshQrCode() {
    if (!this.data.countdownDone) {
      wx.showToast({
        title: '二维码仍在有效期内',
        icon: 'none'
      })
      return
    }
    refreshQrcode({
      sfz: this.data.userInfo.idNumber,
      phone: this.data.userInfo.cellphone,
      name: this.data.userInfo.name,
      signNo: this.data.signNo
    }).then(res => {
      this.setData({
        qrcode: res.qrcode,
        validDate: res.validDate,
        signNo: res.signNo
      })
      this.startQrCountdown(res.validDate)
    })
  },
  startQrCountdown(validDate) {
    this.clearQrCountdown()
    const expireTimestamp = this.parseValidDate(validDate)
    if (!expireTimestamp) {
      this.setData({
        countdownText: '',
        countdownDone: true
      })
      return
    }
    const updateCountdown = () => {
      const diff = expireTimestamp - Date.now()
      if (diff <= 0) {
        this.clearQrCountdown()
        this.setData({
          countdownText: '00:00',
          countdownDone: true
        })
        return
      }
      const totalSeconds = Math.floor(diff / 1000)
      const minutes = Math.floor(totalSeconds / 60)
      const seconds = totalSeconds % 60
      this.setData({
        countdownText: `${this.padTime(minutes)}:${this.padTime(seconds)}`
      })
    }
    updateCountdown()
    this.countdownTimer = setInterval(updateCountdown, 1000)
    this.setData({
      countdownDone: false
    })
  },
  parseValidDate(validDate) {
    if (!validDate) {
      return null
    }
    if (typeof validDate === 'number') {
      return validDate > 1e12 ? validDate : validDate * 1000
    }
    if (/^\d+$/.test(validDate)) {
      const num = Number(validDate)
      return num > 1e12 ? num : num * 1000
    }
    const timeMatch = /^(\d{1,2}):(\d{1,2}):(\d{1,2})$/.exec(validDate)
    if (timeMatch) {
      const now = new Date()
      const target = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate(),
        Number(timeMatch[1]),
        Number(timeMatch[2]),
        Number(timeMatch[3])
      )
      if (target.getTime() <= now.getTime()) {
        target.setDate(target.getDate() + 1)
      }
      return target.getTime()
    }
    const normalized = validDate.replace(/-/g, '/').replace('T', ' ')
    const timestamp = Date.parse(normalized)
    return isNaN(timestamp) ? null : timestamp
  },
  padTime(value) {
    return value < 10 ? `0${value}` : `${value}`
  },
  clearQrCountdown() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer)
      this.countdownTimer = null
    }
  },
  handleRefreshQrDialog() {
    this.refreshQrCode()
  },
  handleCloseQrDialog() {
    this.onClose()
  },
  changeUserInfo() {
    let name = this.data.userInfo.name
    let idNumber = this.data.userInfo.idNumber
    if (!this.data.showUserInfoComplete) {
      let hideName = name.substr(0, 1) + new Array(name.length).join('*');
      let hideIdNumber = idNumber.substr(0, 4) + new Array(idNumber.length - 4).join('*') + idNumber.substr(-4);
      this.setData({
        hideUserInfo: {
          name: hideName,
          idNumber: hideIdNumber,
        }
      })
    } else {
      this.setData({
        hideUserInfo: {
          name: name,
          idNumber: idNumber,
        }
      })
    }
  },
  sctt() {
    wx.setStorageSync('redirect', this.route)
    wx.navigateToMiniProgram({
      path: '/pages/humanSociety/appBear',
      appId: 'wx7aa6ad8c15829d96',
      envVersion: 'trial',
      extraData: {
        appId: '202406040001',
        forwardUrl: "https://rs.jshrss.jiangsu.gov.cn/mobile/person/login?appId=202406040001&returnUrl=/pages/login/index&channelType=JSHRSS_WXSP&thirdAppId=wxeee1e9fe5686a91e",
        from: 'miniapp'
      }
    });
  },
  gotoSbk() {
    wx.navigateToMiniProgram({
      appId: 'wx6163d215ef686f78',
      path: 'pages/home/index',
      success(res) {
        // 打开成功
      }
    })
  },
  jumpMiniProgrand(e) {
    var type = e.currentTarget.dataset.type;
    var name = e.currentTarget.dataset.name;
    saveMatter(name)
    //文旅服务
    if (type == 1) {
      wx.navigateToMiniProgram({
        appId: 'wxfc5e52355ca42762',
        envVersion: 'release'
      })
    } else if (type == 2) {
      // 交通出行
      wx.navigateToMiniProgram({
        appId: 'wx228a58f1d538cc40',
        envVersion: 'release'
      })
    } else if (type == 3) {
      // 交通出行
      wx.navigateToMiniProgram({
        appId: 'wxd68778e4810b78a4',
        envVersion: 'release',
        path: 'pages/userJobIndex/userJobIndex'
      })
    }
  },
  //首页-扫一扫
  getScancode() {
    var that = this;
    // 允许从相机和相册扫码
    wx.scanCode({
      success: (res) => {
        console.log(res);
      }
    })
  },
  //修改搜索栏侧地区定位
  bindChangeAddress(e) {
    this.setData({
      address: this.data.address_List[e.detail.value]
    })
  },
  // 事件处理函数
  jumpPage(e) {
    if (e.currentTarget.dataset.url == '') {
      wx.showToast({
        title: '未配置跳转路径',
        icon: 'error'
      })
      return
    }
    wx.navigateTo({
      url: e.currentTarget.dataset.url
    })
  },
  jumpPageMedical(e) {
    saveMatter('医疗挂号')
    if (wx.getStorageSync('userInfo')) {
      wx.navigateTo({
        url: '/pages/medical/index'
      })
    } else {
      this.sctt()
    }
  },
  jumpPage2(e) {
    if (e.mark.item.type == 2) {
      queryTempFunctionCode(e.mark.item.code).then(res => {
        if (e.mark.item.title == '个人权益单') {
          saveMatter(e.mark.item.title)
        }
        // wx.navigateTo({
        //   url: '/pages/web_h5/web_h5?url=' + encodeURIComponent(res.data)
        // })
        wx.navigateToMiniProgram({
          path: '/pages/humanSociety/appBear',
          appId: 'wx7aa6ad8c15829d96',
          envVersion: 'trial',
          extraData: {
            appId: '202104260001',
            forwardUrl: res.data,
            from: 'miniapp'
          }
        });
      })
    } else if (e.mark.item.type == 3) {
      if (wx.getStorageSync('userInfo')) {
        let sfz = encryptAES(wx.getStorageSync('userInfo').idNumber)
        console.log(sfz)
        // let url = e.mark.item.url + '?id=' + sfz
        let url = e.mark.item.url
        wx.navigateTo({
          url: '/pages/web_h5/web_h5?url=' + encodeURIComponent(url)
        })
      } else {
        this.sctt()
      }
    } else {
      if (e.mark.item.title == '人社服务圈' || e.mark.item.title == '人社智慧大屏') {
        saveMatter(e.mark.item.title)
      }
      if (e.currentTarget.dataset.url == '') {
        wx.showToast({
          title: '未配置跳转路径',
          icon: 'error'
        })
        return
      }
      wx.navigateTo({
        url: e.currentTarget.dataset.url
      })
    }
  },
  gotoPage() {
    wx.navigateTo({
      url: '/pages/web_h5/web_h5?url=' + encodeURIComponent('https://rs.jshrss.jiangsu.gov.cn/sscportal/sbk/2025/')
    })
  },
  gotoPage2() {
    wx.navigateTo({
      url: '/pages/web_h5/web_h5?url=' + encodeURIComponent('https://njrsxxzx.cn/images/html/bankactivity.html')
    })
  },
  // 跳转宁小宝智算第三方页面
  jumpPageNxb() {
    wx.navigateTo({
      url: '/pages/web_h5/web_h5?url=' + encodeURIComponent('https://zstp.njrsxxzx.cn:8582/nj-knowledge-mobile-ui/#/chat')
    })
  },
  // 跳转到h5页面
  jumpPageH5(e) {
    saveMatter('技师学院')
    wx.navigateTo({
      url: '/pages/web_h5/web_h5?url=' + e.currentTarget.dataset.url
    })
  },
  jumpPageDdcz() {
    if (wx.getStorageSync('userInfo')) {
      saveMatter('调度处置')
      getJsapiTicket({
        token: wx.getStorageSync('accessToken'),
      }).then(res => {
        if (res.code == 1000) {
          let url = encodeURIComponent('https://ddcz.njrsxxzx.cn:8072/njjczdddcz/ydbghlwd/index/#/?id=' + wx.getStorageSync('userInfo').idNumber + '&ticket=' + res.ticket)
          wx.navigateTo({
            url: '/pages/web_h5/web_h5?url=' + url
          })
        } else {
          wx.showToast({
            title: 'ticket获取错误！',
          })
        }
      })
    } else {
      this.sctt()
    }
  },
  // 跳转农民工实名制管理
  nmgsmzgl() {
    if (wx.getStorageSync('userInfo')) {
      wx.navigateTo({
        url: '/pages/nmgsmzgl/nmgsmzgl'
      })
    } else {
      this.sctt()
    }
  },
  // 一卡通综合展示
  yktzhzs() {
    if (wx.getStorageSync('userInfo')) {
      wx.navigateTo({
        url: '/pages/zhzs/zhzs'
      })
    } else {
      this.sctt()
    }
  },
  zyzcx() {
    if (wx.getStorageSync('userInfo')) {
      wx.navigateTo({
        url: '/pages/zhzs/detail?type=4'
      })
    } else {
      this.sctt()
    }
  },
  onClose() {
    this.setData({
      showQrCode: false,
      qrcode: '',
      countdownText: '',
      countdownDone: true
    });
    this.clearQrCountdown()
  },
  onLoad(options) { },
  onShow() {
    const route = this.route;
    //设置头部字体与导航栏对齐
    const top = getApp()
    this.setData({
      menuInfo: top.geibartop.menuInfo,
      headHeight: top.globalData.headHeight,
      userInfo: wx.getStorageSync('userInfo'),
      showUserInfoComplete: false
      // login_identification: util.loginOk
    })
    this.changeUserInfo()
  },
  /**
   * 用户点击右上角分享
   */
  onHide() {
    this.clearQrCountdown()
  },
  onUnload() {
    this.clearQrCountdown()
  },
  onShareAppMessage() { }
})